// pages/formTemplate/index.js
import requestUtil from '../../baseRequest.js'
import urls from '../../requestUrl.js'
import { $Message } from '../../components/base/index'

let formTempObject = {}
let uploaderIndex = 0

Page({

    /**
     * 页面的初始数据
     */
    data: {
        components: [],
        testComponent: [],
        formInfo: formTempObject,
        globalVehicleStatus: {},
        test1: [],
        ruleList: [],
        showSpin: false
    },
    changeInput: function(e) {
        console.log('changeInput', e)
    },
    handleClick: function(e) {
        console.log('data', formTempObject)
    },
    addComponent: function(e) {
        let components = this.data.components
        components.push(this.data.testComponent)
        this.setData({
            components: components,
            formInfo: formTempObject
        })
    },
    handleChange({ detail = {} }) {
        console.log('handleChange', detail)
        formTempObject[detail.key] = detail.value
    },
    handleSubmit({ detail }) {
        console.log('form-detail', detail)
        console.log('data', formTempObject)
            //校验表单规则
        if (this.checkFormValueValid(detail.value)) {
            console.log('check true')
                // return
            if (this.data.process == '1') {
                wx.showModal({
                    title: '温馨提示',
                    content: '提交后将无法修改工单信息，是否确定工单信息填写无误并提交信息？',
                    confirmText: '提交',
                    success: res => {
                        if (res.confirm) {
                            this.comfirmToSubmit(detail.value)
                        }
                    }
                })
            } else {
                this.comfirmToSubmit(detail.value)
            }
        }
    },
    comfirmToSubmit(v) {
        wx.pageScrollTo({
            scrollTop: 0,
        })
        this.setData({
            showSpin: true
        })
        this.handleSubmitFormDate(v)
    },
    /**校验表单规则 */
    checkFormValueValid(formData) {
        console.log(this.data.ruleList, formData)
        for (let index = 0; index < this.data.ruleList.length; index++) {
            let _r = this.data.ruleList[index]
            let _rule = _r.rule
            if (_rule.isMust && !formData[_r.key]) {
                this.showErrorMsg(`${_r.name}不能为空`)
                return false
            }
            if (_rule.minlength && formData[_r.key].length < _rule.minlength) {
                this.showErrorMsg(`${_r.name}长度数量不可少于${_rule.minlength}`)
                return false
            }
        }
        return true
    },
    /**显示错误信息提示 */
    showErrorMsg(msg) {
        $Message({
            content: msg,
            type: 'error'
        })
    },
    /**获取表单组件列表信息 */
    getFormComponentsList() {
        let param = {
            "workOrderProcess": this.data.process,
            "workOrderId": this.data.orderId
        }
        requestUtil.postRequest(urls.workOrder.getFormDetail, param, (res) => {
            this.setData({
                components: res,
            })
            this.getUploaderList(res)
        }, () => {})
    },
    /**提取组件中的上传组件 */
    getUploaderList(componentList = []) {
        let list = []
        let _rules = []
        componentList.forEach(group => {
            group.items.forEach(item => {
                if (item.itemType === 'uploader') {
                    list.push(item.code)
                }
                if (item.itemRule) {
                    _rules.push({ 'key': item.code, 'name': item.title, 'rule': item.itemRule })
                }
            })
        })
        this.data.ruleList = _rules
        this.data.uploaderList = list
        return list
    },
    /**触发组件上传图片 */
    handleToUploadImg(itemIndex = 0, formData = {}) {
        let imgs = formData[this.data.uploaderList[itemIndex]] || []
        console.log(imgs)
        imgs.forEach((img, i) => {
            if (img.status != 'success') {
                console.log(i, img)
                this.uploadImageRequest(img.url, (targetFile) => {
                    imgs[i] = targetFile
                })
            }
        })
        if (itemIndex + 1 < this.data.uploaderList.length) {
            this.handleToUploadImg(itemIndex + 1, formData)
        }
    },
    /**上传图片*/
    uploadImageRequest(_filePath, success) {
        wx.uploadFile({
            url: urls.baseUrl + '/api/insurance/image/upload',
            filePath: _filePath,
            name: 'file',
            success: function(res) {
                var data = res.data
                console.log(data)
                let response = JSON.parse(data)
                let targetFile = {}
                targetFile.status = 'success'
                targetFile.url = response.data.url
                targetFile.baseUrl = response.data.baseUrl
                success(targetFile)
            },
            fail: function(res) {
                console.log('uploader fail', res)
            },
            complete: function() {
                // complete
            }
        })
    },
    /**
     * 转换表单数据 
     */
    translateFormData(data) {
        let target = []
        for (let i in data) {
            console.log('formKey:' + i)
            let p = { "key": i, "value": data[i] }
            target.push(p)
        }
        return target
    },
    /**处理表单的提交数据 */
    handleSubmitFormDate(formData) {
        //处理上传组件
        if (this.data.uploaderList.length > 0) {
            this.handleToUploadImg(0, formData)
            this.checkImgUploadStatus(formData)
        } else {
            let formParam = this.translateFormData(formData)
            console.log('formParam', formParam)
            this.commitFormValue(formParam)
        }

    },
    /**检查图片上传是否成功 */
    checkImgUploadStatus(formData) {
        for (let index = 0; index < this.data.uploaderList.length; index++) {
            console.log('index', index)
            const key = this.data.uploaderList[index];
            let imgs = formData[key]
            for (let i = 0; i < imgs.length; i++) {
                const img = imgs[i];
                console.log(i, img.status)
                if (img.status != 'success') {
                    setTimeout(() => {
                        this.checkImgUploadStatus(formData)
                    }, 300)
                    return
                }
            }
        }
        console.log('finish for')
        let formParam = this.translateFormData(formData)
        console.log('formParam', formParam)
        this.commitFormValue(formParam)
    },
    /**提交表单信息 */
    commitFormValue(formValue) {

        // return
        let param = {
            val: formValue,
            workOrderProcess: this.data.process
        }
        requestUtil.postRequest(urls.workOrder.updateOrderForForm + this.data.orderId, param, (res) => {
            console.log(res)
            this.setData({
                showSpin: false
            })
            wx.showToast({
                icon: 'success',
                title: '提交成功',
            })
            if (this.data.routerFrom == 'process') {
                wx.navigateBack()
            } else {
                wx.redirectTo({
                    url: '/pages/workOrder/orderProcess/index?orderid=' + this.data.orderId
                })
            }
        }, () => {})
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        let orderId = options.orderId || ''
        let process = options.process || '0'
        let routerFrom = options.routerFrom || ''
        this.setData({
            orderId,
            process,
            routerFrom,
        })
        this.getFormComponentsList()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        this.setData({
            signPaths: getApp().globalData.signTempPath,
            globalVehicleStatus: getApp().getVehicleStatus(),
            agreements: getApp().getAgreementsStatus()
        })
        console.log('signPaths', this.data.signPaths)
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        getApp().clearGlobalValue()
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    // onShareAppMessage: function() {

    // }
})